// pages/message/chart/index.js
const httpUtils = require('../../../utils/httpUtils')
const ui = require('../../../utils/ui')
const util = require('../../../utils/util')
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        content: '',
        // 当前登录者信息
        login: {},
        page: {
            pageNo: 1,
            pageSize: 100
        },
        // 聊天信息
        letterList: [],
        userid: 0,
        inter: '',
        aimgurl: "", // //临时图片的路径
        countIndex: 1, // 可选图片剩余的数量
        imageData: [], // 所选上传的图片数据
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let id = options.userid
        let _this = this
        this.setData({
            login: app.globalData.userInfo,
            userid: id,
        })
        this.getMessageList(id);
        this.scrollToBottom();
        // _this.data.inter = setInterval(
        //     function () {
        //         // TODO 你需要无限循环执行的任务
        //         _this.getMessageList(id);
        //         console.log('setInterval 每过500毫秒执行一次任务')
        //     }, 500);
    },
    getMessageList(id) {
        let conversationId = ''
        if (id > this.data.login.id) {
            conversationId = this.data.login.id + '_' + id;
        } else {
            conversationId = id + '_' + this.data.login.id;
        }
        var _this = this
        // 获取就诊卡列表
        httpUtils.request({
            method: "POST",
            // showLoading: true,
            url: `/api/letter/detail/` + conversationId,
            data: _this.data.page,
            message: "获取聊天列表...",
        }).then(res => {
            // console.log(res)
            if (res.data.code != 0) {
                ui.showToast(res.data.mes)
            } else {
                wx.setNavigationBarTitle({
                    title: res.data.data.conversations[0].target.nickname + '医生' //页面切换，更换页面标题
                })
                for (let i = 0; i < res.data.data.conversations.length; i++) {
                    res.data.data.conversations[i].conversation.time = util.parseTime(res.data.data.conversations[i].conversation.created_at)
                    if (res.data.data.conversations[i].conversation.from_id == _this.data.login.id) {
                        res.data.data.conversations[i].target = _this.data.login
                    }
                }
                _this.setData({
                    letterList: res.data.data.conversations
                })

                console.log(_this.data.letterList)
            }
        }).catch(err => {
            console.log(err)
        });
    },
    // 输入监听
    inputClick(e) {
        this.setData({
            content: e.detail.value
        })
    },
    // 发送监听
    sendClick() {
        var that = this;
        var list = this.data.letterList;
        // 获取当前时间
        var date = new Date();
        var month = date.getMonth() + 1;
        var day = date.getDate();
        var hour = date.getHours();
        var minu = date.getMinutes();
        var now1 = month < 10 ? '0' + month : month;
        var now2 = day < 10 ? '0' + day : day;
        // 组装数据
        var msg = {
            conversation: {
                content: this.data.content,
                from_id: this.data.login.id,
                time: now1 + '-' + now2 + ' ' + hour + ':' + minu,
            },
            target: this.data.login
        }
        this.setData({
            letterList: list.concat(msg)
        }, () => {
            that.scrollToBottom();
            // 发送消息给服务器
            var _this = this
            httpUtils.request({
                method: "POST",
                // showLoading: true,
                url: `/api/letter/send_letter`,
                data: {
                    to_user_id: _this.data.userid,
                    content: _this.data.content,
                },
                message: "获取聊天列表...",
            }).then(res => {
                // console.log(res)
                if (res.data.code != 0) {
                    ui.showToast(res.data.mes)
                } else {
                    console.log(res)
                }
            }).catch(err => {
                console.log(err)
            });
            that.setData({
                content: ''
            })
        })

    },
    // 滑动到最底部
    scrollToBottom() {
        setTimeout(() => {
            wx.pageScrollTo({
                scrollTop: 200000,
                duration: 3
            });
        }, 600)
    },
    /*图片浏览及上传 */
    browse: function (e) {
        let that = this;
        wx.showActionSheet({
            itemList: ['从相册中选择', '拍照', '上传文件'],
            itemColor: "#CED63A",
            success: function (res) {
                if (!res.cancel) {
                    if (res.tapIndex == 0) {
                        that.chooseWxImage('album');
                    } else if (res.tapIndex == 1) {
                        that.chooseWxImage('camera');
                    } else if (res.tapIndex == 2) {
                        that.chooseWxImage('file');
                    }
                }
            }
        })
    },

    /*打开相册、相机 */
    chooseWxImage: function (type) {
        let that = this;
        wx.chooseImage({
            count: that.data.countIndex,
            sizeType: ['original', 'compressed'],
            sourceType: [type],
            success: function (res) {
                // 选择图片后的完成确认操作
                that.setData({
                    aimgurl: res.tempFilePaths
                });
                console.log(that.data.aimgurl);
                that.upLoadImgFun(res.tempFilePaths);
            }
        })
    },
    /**上传：图片到服务器 */
    upLoadImgFun: function (tempFilePathsData) {
        let that = this;
        let orderCommentMaterial = []; // 每次选择添加的图片并上传到服务器后的图片信息
        tempFilePathsData.forEach((item, index) => {
            wx.uploadFile({
                url: 'http://localhost:8888/api/image_upload', // 上传服务器的后台请求接口地址
                filePath: item, // 要上传的图片数据对象
                name: 'image', // 上传类型
                header: {
                    'content-Type': 'multipart/form-data' // 此处加上，用form表单的格式传
                },
                // 要携带的参数
                formData: {
                    business: 'images'
                },
                success(res) {
                    let data = JSON.parse(res.data)
                    console.log(data.data.url);
                    var list = that.data.letterList;
                    var msg = {
                        conversation: {
                            content: data.data.url,
                            from_id: that.data.login.id,
                            // time: now1 + '-' + now2 + ' ' + hour + ':' + minu,
                            type: 1
                        },
                        target: that.data.login
                    }
                    that.setData({
                        letterList: list.concat(msg)
                    }, () => {
                        that.scrollToBottom();
                        // 发送消息给服务器
                        var _this = that
                        httpUtils.request({
                            method: "POST",
                            // showLoading: true,
                            url: `/api/letter/send_letter/image`,
                            data: {
                                to_user_id: _this.data.userid,
                                content: data.data.url,
                            },
                            message: "获取聊天列表...",
                        }).then(res => {
                            // console.log(res)
                            if (res.data.code != 0) {
                                ui.showToast(res.data.mes)
                            } else {
                                console.log(res)
                            }
                        }).catch(err => {
                            console.log(err)
                        });
                        that.setData({
                            content: ''
                        })
                    })
                },
                fail(err) {
                    console.log(err);
                },
                complete(all) {
                    console.log(all.data);
                }
            });
        });
    },
    previewImg(e) {
        console.log(e.currentTarget.dataset.url)
        wx.previewImage({
            current: e.currentTarget.dataset.url, // 当前显示图片的http链接
            urls: [e.currentTarget.dataset.url] // 需要预览的图片http链接列表
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {
        let _this = this
        _this.clearInterval(_this.data.inter)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})